<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>Password List</title>

    <!-- Bootstrap -->
    <link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/signin.css" rel="stylesheet">
    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
      #key{
        display: inline;
        width: 60%;
      }
      #add{
        float: right;
      }
      #search_text{
        display: inline;
        width: 30%;
      }
      .search{
        float: right;
      }
      #more_button{
        width: 100%;
      }
    </style>
  </head>
  <body>
    <!-- <h1>你好，世界！</h1> -->
    <div class="container">

      <div class="col-md-12">
          <input type="password" id="key" class="form-control" placeholder="key" required>
          <button type="button" class="btn btn-sm btn-primary" id="add"  data-toggle="modal" data-target="#myModal">Add</button>

          <br><br>
          <button type="button" class="btn btn-sm btn-primary search" id="search_button">Search</button>
          <input type="text" id="search_text" class="form-control search" placeholder="search by description" required>
          
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>Description</th>
                <th>Username</th>
                <th>Password</th>
                <th>Operation</th>
              </tr>
            </thead>
            <tbody id="list">
            <!-- <tr>
              <td>密码描述</td>
              <td>用户名</td>
              <td class="password_value">OC6EBR7NFNN1sUyUyOH6dA==</td>
              <td><button type="button" class="btn btn-xs btn-danger">Delete</button></td>
            </tr> -->
            </tbody>
          </table>
          <button id="more_button" type="button" class="btn btn btn-default">more</button>
          <!-- 添加密码数据模态框 -->
          <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">添加新的密码</h4>
                </div>
                <div class="modal-body">
                  <input type="text" id="desc_input" class="form-control search" placeholder="description" required>
                  <input type="text" id="name_input" class="form-control search" placeholder="username" required>
                  <input type="text" id="value_input" class="form-control search" placeholder="password" required>
                </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="add_button">提交更改</button>
                  </div>
                </div><!-- /.modal-content -->
              </div><!-- /.modal -->
          </div>
          
        </div>

    </div>

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script src="bootstrap-3.3.7-dist/js/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <!-- 加解密所用库 -->
    <script type="text/javascript" src="CryptoJS/rollups/aes.js"></script>
	  <script type="text/javascript" src="CryptoJS/components/mode-ecb.js"></script>
    <!-- 加密所用函数 -->
    <script type="text/javascript" src="js/password.js"></script>
    <!-- 工具函数 -->
    <script type="text/javascript" src="js/tool.js"></script>
    <script type="text/javascript">
      last_id = 0;
      temp = "";
      url = "api/password/get"
      // 填充函数
      function pad(list){
        for(var i = 0; i < list.length; i++){
          // 添加数据
          $('#list').append('<tr><td>' + list[i].keyword + '</td><td id="name' + list[i].id + '">' + list[i].name + '</td><td class="password_value" onmouseover="on_decrypt(' + list[i].id +')" onmouseout="out_decrypt(' + list[i].id + ')" id="value' + list[i].id + '"  >' + list[i].value + '</td><td><button type="button" class="btn btn-xs btn-danger" onclick="deletePass(' + list[i].id + ')">Delete</button></td></tr>')
          // 更新最后一个得到的id
          last_id = list[i].id;
        }
      }

      // 根据url来填充数据
      function pad_list_by_url(url){
        $.get(url + "lastId=" + last_id,{},function(str){

          var res = eval('(' + str + ')')
          if(res.code !==0){
            if(res.code == 1024){
              last_id = 0;
              window.location.href = 'index.html';
              return
            }
            alert(res.message);
            return;
          }
          pad(res.obj)
        })
      }
      // 搜索按钮的点击事件
      $('#search_button').click(function(){
        // 如果没有输入关键字
        if(isEmpty($('#search_text'))){
          // 清空并加载新的页面
          last_id = 0;
          $('#list').empty()
          url = "api/password/get?"
          pad_list_by_url(url);
          return
        }else{
          // 如果要搜索某个关键字
          // 清空并加载新的页面
          last_id = 0;
          $('#list').empty()
          url = "api/password/search?keyword=" + $('#search_text').val() + '&';
          pad_list_by_url(url);
        }
      })
      $('#more_button').click(function(){
        pad_list_by_url(url)
      })

      // 鼠标移入解密
      function on_decrypt(id){
        if(isEmpty($('#key'))){
          // console.log('钥匙为空')
          return;
        }
        obj = $('#value' + id);
        temp = obj.text();
        // console.log(temp)
        let crypto_text = obj.text();
        let key = $('#key').val();
        let name = $('#name' + id).text()
        let decrypt_text = decrypt(crypto_text, key)
        // 计算原本内容
        decrypt_text = decrypt_text.substr(name.length)

        obj.text(decrypt_text)
      }


      // 鼠标移出加密
      function out_decrypt(id){
        if(isEmpty($('#key'))){
          // console.log('钥匙为空')
          return;
        }
        $('#value' + id).text(temp)
      }

      // 当文档准备就绪后执行
      $(document).ready(function(){
        url = "api/password/get?"
        pad_list_by_url(url);
        // 密码上用于加解密的事件
      
      });
      // pad([{'keyword':'add','name':'test','value':'123456'}])
      // 删除密码的函数
      function deletePass(id){
        if(!confirm('是否删除这条密码数据？')){
          return ;
        }
        var data = {'id':id};
        // 发送删除的消息
        $.post('api/password/delete',data,function(str){
          var res = eval('(' + str + ')');
          if(res.code !==0){
            alert(res.message)
          }else{
            last_id=0;
            $('#list').empty()
            pad_list_by_url(url)
          }
        })
      }
      
      

      // 点击添加密码之后的事件
      $('#add_button').click(function(){
        let keyword = $('#desc_input').val();
        let name = $('#name_input').val();
        let raw_value = $('#value_input').val();
        let key = $('#key').val()

        if(isBlank(keyword)){
          alert('描述用于寻找密码不可为空')
          return;
        }
        if(isBlank(name)) {
          alert('用户名不能为空');
          return;
        }
        if(isBlank(raw_value)) {
          alert('密码值不可为空');
          return;
        }
        if(isBlank(key)) {
          alert('钥匙不可为空');
          return;
        }
        let value = encrypt(name + raw_value, key);
        var data = {
          'keyword':keyword,
          'name': name,
          'value': value
        }
        // console.log(JSON.stringify(data))
        $.post('api/password/add',data,function(str){
          let res = eval('(' + str + ')')
          if (res.code === 0){
            $('#myModal').modal('hide');
            alert('添加成功')
            // 直接添加到列表中最前面
            let newId = res.obj;
            $('#list').prepend('<tr>' +
                    '<td>' + keyword + '</td>' +
                    '<td>' + name + '</td>' +
                    '<td class="password_value" onmouseover="on_decrypt(' + newId +')" onmouseout="out_decrypt(' + newId + ')" id="value' + newId + '"  >' + value + '</td>' +
                    '<td><button type="button" class="btn btn-xs btn-danger" onclick="deletePass(' + newId + ')">Delete</button></td>' +
                    '</tr>')
            $('#desc_input').val('');
            $('#name_input').val('');
            $('#value_input').val('');
          }else{
            alert(res.message);
          }
        })
      })

    </script>
  </body>
</html>

